package com.lmaye.retrying;

import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryListener;
import com.lmaye.App;
import com.lmaye.utils.DingTalkUtlis;
import com.lmaye.utils.GsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;

/**
 * -- 请求重试监听器
 *
 * @author lmay.Zhou
 * @date 2019/6/10 17:17 星期一
 * @qq 379839355
 * @email lmay@lmaye.com
 */
@Slf4j
public class RequestRetryListener<BaseResponse> implements RetryListener {
    @Override
    @SuppressWarnings({"unchecked", "TypeParameterHidesVisibleType"})
    public <BaseResponse> void onRetry(Attempt<BaseResponse> attempt) {
        // 第几次重试
        long attemptNumber = attempt.getAttemptNumber();
        log.info("[retry] times : {}", attemptNumber);
        // 是否有异常
        if (attempt.hasException()) {
            log.error("[retry] exception: ", attempt.getExceptionCause());
        }
        // 是否有结果
        if (attempt.hasResult()) {
            if (Objects.isNull(attempt.getResult())) {
                log.info("[retry] return data is null");
            } else {
                log.info("[retry] return data is:{}", GsonUtils.toJson(attempt.getResult()));
            }
        }
        Map<String, Object> appProperties = App.APP_PROPERTIES;
        Map<String, Integer> retryingProperties = (Map<String, Integer>) appProperties.get("retrying");
        // 如果重复3次，则发消息通知
        if(Objects.equals(retryingProperties.get("retryTimes").longValue(), attemptNumber)) {
            log.error("-------------------> Send Massage <-------------------");
            // 发送钉钉消息
            if (attempt.hasException()) {
                DingTalkUtlis.sendMsg(attempt.getExceptionCause().toString());
            }
            if (attempt.hasResult() && Objects.nonNull(attempt.getResult())) {
                DingTalkUtlis.sendMsg(GsonUtils.toJson(attempt.getResult()));
            }
        }
    }
}
